package com.dms.modules.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.modules.community.entity.CommunityAudit;
import com.dms.modules.community.mapper.CommunityAuditMapper;
import com.dms.modules.community.service.CommunityAuditService;
import com.dms.modules.message.dto.MessageDetailDTO;
import com.dms.modules.message.websocket.MessageWebSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Slf4j
@Service
public class CommunityAuditServiceImpl extends ServiceImpl<CommunityAuditMapper, CommunityAudit> implements CommunityAuditService {

    // 简单的敏感词列表，实际应该从数据库或配置文件加载
    private static final Set<String> SENSITIVE_WORDS = new HashSet<>(Arrays.asList(
            "暴力", "色情", "赌博", "毒品", "政治"
    ));
    
    @Autowired
    private MessageWebSocket messageWebSocket;

    @Override
    public boolean containsSensitiveWords(String content) {
        if (content == null || content.isEmpty()) {
            return false;
        }
        
        // 简单的敏感词检测
        return SENSITIVE_WORDS.stream().anyMatch(content::contains);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createAudit(Integer targetType, Long targetId) {
        try {
            CommunityAudit audit = new CommunityAudit()
                .setContentType(targetType)
                .setContentId(targetId)
                .setStatus(0) // 待审核
                .setCreateTime(LocalDateTime.now())
                .setUpdateTime(LocalDateTime.now());
            
            save(audit);
            return audit.getId();
        } catch (Exception e) {
            log.error("创建审核记录失败: targetType={}, targetId={}, error={}", 
                    targetType, targetId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean audit(Long id, Integer status, String reason, Long auditorId) {
        try {
            CommunityAudit audit = getById(id);
            if (audit == null) {
                return false;
            }
            
            audit.setStatus(status)
                .setRemark(reason)
                .setAuditorId(auditorId)
                .setAuditTime(LocalDateTime.now())
                .setUpdateTime(LocalDateTime.now());
            
            boolean success = updateById(audit);
            if (success) {
                // 发送审核结果通知
                sendAuditNotification(audit);
            }
            
            return success;
        } catch (Exception e) {
            log.error("审核失败: id={}, status={}, error={}", id, status, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public Integer getAuditStatus(Integer targetType, Long targetId) {
        try {
            LambdaQueryWrapper<CommunityAudit> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CommunityAudit::getContentType, targetType)
                   .eq(CommunityAudit::getContentId, targetId)
                   .orderByDesc(CommunityAudit::getCreateTime)
                   .last("LIMIT 1");
            
            CommunityAudit audit = getOne(wrapper);
            return audit != null ? audit.getStatus() : null;
        } catch (Exception e) {
            log.error("获取审核状态失败: targetType={}, targetId={}, error={}", 
                    targetType, targetId, e.getMessage(), e);
            throw e;
        }
    }
    
    /**
     * 发送审核结果通知
     */
    private void sendAuditNotification(CommunityAudit audit) {
        try {
            MessageDetailDTO message = new MessageDetailDTO();
            message.setType(1); // 1-系统通知
            message.setTitle("内容审核通知");
            
            String targetType = audit.getContentType() == 1 ? "帖子" : "评论";
            String result = audit.getStatus() == 1 ? "通过" : "拒绝";
            String reason = audit.getStatus() == 2 ? "，原因：" + audit.getRemark() : "";
            
            message.setContent(String.format("您的%s审核%s%s", targetType, result, reason));
            // TODO: 设置接收者ID（需要从帖子或评论中获取作者ID）
            
            messageWebSocket.sendMessage(1L, message); // 临时hardcode接收者ID
        } catch (Exception e) {
            log.error("发送审核通知失败: auditId={}, error={}", audit.getId(), e.getMessage(), e);
        }
    }
} 